package com.gitxinghui;

import java.util.concurrent.locks.ReentrantLock;

public class PrintNumberRunnable2 implements Runnable {


    private int num = 1;    // 计数器
    private final ReentrantLock lock = new ReentrantLock(true); // 使用公平锁

    @Override
    public void run() {
        while (true) {
            if (num <= 100) {
                try {
                    // 加锁
                    lock.lock();
                    if (num > 100) {
                        break;
                    }
                    System.out.println(Thread.currentThread().getName() + "打印数字：" + num++);
                } finally {
                    // 释放锁
                    lock.unlock();
                }
            } else {
                break;
            }
        }
        System.out.println(Thread.currentThread().getName() + "执行完毕");
    }
}
